<template>
    <div class="relative  h-full w-full transition-width flex flex-col overflow-hidden items-stretch flex-1">
        <div class=" flex-1 overflow-hidden">
            <template v-if="chatList.length == 0">
                <h3 class=" text-default font-semibold text-center text-4xl mt-12">ChatGpt</h3>
                <recommend @ask="askRecommend" />
            </template>
            <list v-else />

        </div>

        <div class=" border-none fixed bottom-0 md:pl-52 left-0 w-full border-t bg-transparent md:border-t-0 ">
            <div class="stretch flex flex-row gap-3 pt-2 last:mb-6 md:last:mb-8 lg:mx-auto lg:max-w-3xl lg:pt-6">
                <div class="relative flex h-full flex-1 flex-col gap-2">
                    <div v-show="askStatus" class="flex ml-1 mt-1.5 md:w-full md:m-auto mb-2 gap-2 justify-center">
                        <button @click="stop"
                            class=" bg-[#ecca88] border-[#ecca88] btn flex justify-center gap-2 border md:border py-2 px-4"
                            title="中止">
                            <img class=" w-6" src="@/assets/stop.png" alt="" srcset="">
                            终止生成
                        </button>
                    </div>
                    <div class="flex align-middle gap-x-2 mb-2 flex-1">
                        <div
                            class="flex flex-col w-full py-2 flex-grow md:pl-4 relative border border-solid border-black/10 bg-white dark:border-gray-900/50 dark:text-white dark:bg-gray-700 rounded-md shadow-dark-50 dark:shadow-[0_0_15px_rgba(0,0,0,0.10)]">
                            <textarea @keydown="keydown" v-model="content" placeholder="请输入提问" size="large"
                                class="placeholder-gray-500 outline-none m-0 w-full resize-none border-0 bg-transparent p-0 pl-2 pr-7 focus:ring-0 focus-visible:ring-0 dark:bg-transparent md:pl-0"
                                style="max-height: 200px; height: 24px; color: inherit;"></textarea>
                            <a alt="111" @click="router.push({ name: 'tags' })"
                                class="absolute p-2 rounded-md text-gray-500 right-[4rem] bottom-1 md:right-[4.5rem] top-0.4 hover:bg-gray-100 dark:hover:text-gray-400 dark:hover:bg-gray-900 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent">
                                <span role="img" aria-label="send" class="anticon anticon-send">
                                    词
                                </span>
                            </a>
                            <input accept="image/*" type="file" id="img" hidden>
                            <label for="img"
                                class="absolute p-2 rounded-md text-gray-500 right-8 top-0.5 bottom-1 md:right-10 hover:bg-gray-100 dark:hover:text-gray-400 dark:hover:bg-gray-900 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent">
                                <span role="img" aria-label="send" class="anticon anticon-send">
                                    <img class=" w-5 h-5" src="@/assets/camera.svg" alt="" srcset="">
                                </span>
                            </label>
                            <a @click="search"
                                class="absolute p-2 rounded-md text-gray-500 right-1 bottom-1 md:right-2 top-0.5 hover:bg-gray-100 dark:hover:text-gray-400 dark:hover:bg-gray-900 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent">
                                <span role="img" aria-label="send" class="anticon anticon-send">
                                    <img class=" w-4 h-4" src="@/assets/fasong.svg" alt="" srcset="">
                                </span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 关键词筛选 -->
        <keyword :show="showKeyWord" :words="words" @confirmSearch="confirmSearch" @cancel="showKeyWord = false" />

        <!-- 充值提示 -->
        <recharge :show="showRecharge" @cancel="showRecharge = false" />
    </div>
</template>

<script lang='ts' setup>
import recommend from '@/pages/chats/recommend.vue';
import {
    complete_question,
    count_stop,
    create_question,
    get_chats_detail,
    ocr,
    start_response
} from '@/request/api';
import main from '@/store/index';
import { beforeRead, dataURLtoBlob } from '@/utils/imghandler';
import client from '@/utils/oss';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import keyword from './keyword.vue';
import list from './list.vue';
import recharge from './recharge.vue';
const router = useRouter()
const emits = defineEmits(['getData'])
const route = useRoute()
const { chatList, askStatus, askContent, cancel, loading } = storeToRefs(main())
let content = ref('')
let words = ref<[]>([]) //识别的关键词
let showKeyWord = ref<boolean>(false) //展示内容选择
let showRecharge = ref<boolean>(false)  //展示充值页面
let es: any
const props = withDefaults(
    defineProps<{
        id: string
        keyword?: string
    }>(),
    {
        id: '',
    }
)
let question_res = reactive({
    id: null,
    prompt: ''
})

const search = () => {
    if (askStatus.value == 1) return
    if (!content.value.trim() || !content.value.replace(/\\n/gi, '')) {
        window.alert('输入问题不能为空')
        return
    }

    create_question({
        content: content.value,
        chat_id: route.params.id as string,
    }).then((res) => {
        if (res.code == 200) {
            question_res = Object.assign(question_res, res.result) // 创建问题时返回的信息
            if (chatList.value.length == 0) {
                emits('getData')
            }
            let question = {
                type: 'ask',
                content: content.value,
            }
            chatList.value.push(question)
            askStatus.value = 1 //等待回答
            const params = JSON.parse(JSON.stringify(content.value))
            content.value = ''

            let es = fetchEventSource("https://api.chatai.gd.cn/completions", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    signature: res.result.signature,
                    question_id: res.result.id,
                    messages: res.result.messages
                }),
                onmessage(res) {
                    if (!askContent.value && res.data) {
                        start_response({ id: question_res.id })
                    }
                    if (res.data === '$done$') {
                        es.close()
                        complete_question({
                            id: question_res.id,
                            content: askContent.value,
                        }).then((res) => {
                            if (res.code == 200) {
                                askStatus.value = 0
                                chatList.value.push({
                                    type: 'robot',
                                    content: askContent.value,
                                })
                            }
                            askContent.value = ''
                        })
                    } else {
                        let data = res.data.replace(/\/n/gi, '\n')
                        askContent.value += data
                    }
                },
                onerror(err) {
                    message.error('请求错误！')
                    throw new Error(err)
                }
            });
            es.then(res)
        } else if (res.code == 208) {
            chatList.value.push({
                type: 'ask',
                content: content.value,
            })
            content.value = ''
            chatList.value.push({
                type: 'robot',
                content: res.message
            })
            askContent.value = ''
            showRecharge.value = true
        }
    })
}
const stop = () => {
    es.close()
    chatList.value.push({
        type: 'robot',
        content: askContent.value,
    })
    count_stop({ id: question_res.id, content: askContent.value })
    askContent.value = ''
    askStatus.value = 0
}
const getData = () => {
    get_chats_detail(route.params.id as string).then((res) => {
        if (res.code == 200) {
            chatList.value = []
            res.result.questions.reverse().forEach((item: any) => {
                chatList.value = [
                    ...chatList.value,
                    ...[
                        {
                            type: 'question',
                            content: item.content,
                        },
                        {
                            type: 'robot',
                            content: item.answer ?? '',
                        },
                    ],
                ]
            })
        }
    })
}
const keydown = (e: KeyboardEvent) => {
    if (e.key == 'Enter') {
        if (!e.isComposing) {
            search()
        }
        e.preventDefault()
        return
    }
}
onMounted(() => {
    if (route.query.keyword) {
        content.value = route.query.keyword as string
        search()
    } else {
        getData()
    }
    ; (document.querySelector('#img') as HTMLInputElement).addEventListener(
        'change',
        async (e: Event) => {
            loading.value = true
            const file = ((e?.target as HTMLInputElement).files as FileList)[0]

            content.value = ''
            const formData = new FormData()
            formData.append('file', file)
            let resultImg: any = await beforeRead(file)
            resultImg = dataURLtoBlob(resultImg)
            try {
                const result = await client.put(
                    dayjs(new Date()).format('YYYYMMDDhhmmss') + file.name,
                    resultImg
                )
                if (result.res.status == 200) {
                    const formData = new FormData()
                    formData.append('url', result.url)
                    ocr(formData).then((res) => {
                        if (res.code == 200) {
                            loading.value = false
                            showKeyWord.value = true
                            words.value = res.result.words
                        } else {
                            loading.value = false
                        }
                    })
                }
            } catch (e) {
                loading.value = false
            }
        }
    )
})
const askRecommend = (keyword: string) => {
    content.value = keyword
    search()
}
const confirmSearch = (keyword: string) => {
    content.value = keyword
    showKeyWord.value = false
}
</script>
<style>
::-webkit-input-placeholder {
    /* WebKit browsers，webkit内核浏览器 */
    color: #ccc;
    font-size: 16px;
}
</style>